package com.dongnao.network.bio;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author sjy
 * @date 2024年05月09日 16:15
 */
public class DatagramClient {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName("localhost");
        int port = 20000;

        // 发送数据给服务器
        byte[] data = "你好我是客户端".getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        socket.send(packet);//发送UDP数据包

        // 接收服务器的数据
        byte[] buffer = new byte[1024];
        DatagramPacket packet2 = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet2);//接收UDP数据包
        System.out.println("服务器响应：");
        System.out.println("数据：" + new String(packet2.getData()) + " 偏移量" + packet2.getOffset() + " 长度" + packet2.getLength());
        socket.close();
    }
}
